package com.outsourcing.bottle.ui;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONObject;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.text.Html;
import android.text.TextUtils;
import android.view.ContextThemeWrapper;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.outsourcing.bottle.BasicActivity;
import com.outsourcing.bottle.R;
import com.outsourcing.bottle.db.LanguageConfigTable;
import com.outsourcing.bottle.domain.FriendEntry;
import com.outsourcing.bottle.domain.FriendGroupEntry;
import com.outsourcing.bottle.domain.InitFriendInfo;
import com.outsourcing.bottle.domain.LanguageConfig;
import com.outsourcing.bottle.domain.ShowtipsEntry;
import com.outsourcing.bottle.domain.UrlConfig;
import com.outsourcing.bottle.remoteimage.RemoteImageView;
import com.outsourcing.bottle.util.AppContext;
import com.outsourcing.bottle.util.BasicUIEvent;
import com.outsourcing.bottle.util.HttpUtils;
import com.outsourcing.bottle.util.ServiceUtils;
import com.outsourcing.bottle.util.StringUtil;
import com.outsourcing.bottle.util.TextUtil;
import com.outsourcing.bottle.util.UICore;
import com.outsourcing.bottle.widget.CustomListView;
/**
 * 
 * @author 06peng
 *
 */
public class ChooseFriendActivity extends BasicActivity implements BasicUIEvent, OnClickListener, Callback {
	
	private static final String TAG = ChooseFriendActivity.class.getSimpleName();
	private final int init_friend_info = 1;
	private final int init_friend_info_error = 2;
	private final int load_more_datas = 3;
	private final int init_has_exs = 4;
	private final int init_has_exs_error = 5;
	private final int refresh_friend = 6;
	private final int init_friend_myfriend_no_data = 7;
	private final int init_friend_btfriend_no_data = 8;
	private final int recommend_photo = 9;
	private final int error = 10;
	
	private ImageView backView;
	private TextView titleView;
	private ImageButton confirmView;
	private LinearLayout friendGroupLayout;
	private TextView groupNameView;
	private ViewHolder holder;
	
	private List<FriendEntry> friendList;
	private List<FriendGroupEntry> friendGroupList;
	private FriendAdapter adapter;
	private String[] groupNames;
	private int groupItem;
	private int chooseFriendType;
	/**0：好友     1：瓶友*/
	private int listType;
	private int page = 1;
	private int count = 20;
	private int groupId;
	private int ouid;
	private int lastItem;
	
	private CustomListView listView;
	private ProgressBar progressBar;
	private TextView loadMoreView;
	private int pic_uid;
	private int picid;
	private int bottleId;
	private int exchange_type;
	private int select_mode;
	private Handler handler;
	private ShowtipsEntry show_config;
	private View mheaderView;
	private RelativeLayout mNoDataTipsLayout;
	private TextView mNoDataTipsText1;
	private TextView mNoDataTipsText2;
	private Button mNoDataTipsButton;
	private String return_type = "";

	

	@Override
	protected void onCreate(Bundle paramBundle) {
		super.onCreate(paramBundle);
		handler = new Handler(this);
		setContentView(R.layout.choose_friend);
		chooseFriendType = getIntent().getIntExtra("choose_friend_type", 0);
		picid = getIntent().getIntExtra("picid",0);
		pic_uid = getIntent().getIntExtra("pic_uid",0);
		bottleId = getIntent().getIntExtra("bttype_id", 0);
		return_type = getIntent().getStringExtra("return_type");
		if (chooseFriendType == AppContext.CHOOSE_FRIEND_THROWBOTTLE_TYPE) {  //扔瓶子
			listType = 0;
		} else if (chooseFriendType == AppContext.CHOOSE_FRIEND_EXCHANGE_INFO_TYPE) {//交换资料
			listType = 1;
			exchange_type = 1;
			select_mode = 0;
		} else if(chooseFriendType == AppContext.CHOOSE_FRIEND_EXCHANGE_PHOTO_TYPE) {//交换照片
			listType = 1;
			exchange_type = 0;
			select_mode = 0;
		} else if (chooseFriendType == AppContext.CHOOSE_FRIEND_FORWARD_BOTTLE_TYPE) {//转发瓶子给好友
			listType = 0;
			select_mode = 1;
			groupId = -1;
		} else if (chooseFriendType == AppContext.CHOOSE_FRIEND_FORWARD_PHOTO_TYPE) {//转发照片给好友
			listType = 0;
			select_mode = 0;
			groupId = -1;
		}
		select_mode = getIntent().getIntExtra("select_mode", 0);
		initWidget();
		setUIbyType();
		UICore.eventTask(this, this, init_friend_info, getString(R.string.init_data), null);
	}	
	private void initWidget() {
		backView = (ImageView) findViewById(R.id.topbar_back);
		backView.setOnClickListener(this);
		confirmView = (ImageButton) findViewById(R.id.topbar_confirm);
		confirmView.setOnClickListener(this);
		titleView = (TextView) findViewById(R.id.topbar_title);
		titleView.setText(getString(R.string.choose_friend_select));
		friendGroupLayout = (LinearLayout) findViewById(R.id.choose_friend_layout);
		friendGroupLayout.setOnClickListener(this);
		groupNameView = (TextView) findViewById(R.id.choose_friend_group_name);
  		listView = (CustomListView) findViewById(R.id.choose_friend_list);
		listView.setonRefreshListener(new CustomListView.OnRefreshListener() {
			
			@Override
			public void onRefresh() {
				page = 1;
				UICore.eventTask(ChooseFriendActivity.this, ChooseFriendActivity.this, init_friend_info, null, null);
			}
		});
		listView.setOnScrollListener(new OnScrollListener() {
			
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				if (lastItem == adapter.getCount() - 1 && scrollState == OnScrollListener.SCROLL_STATE_IDLE) {
					page++;
					progressBar.setVisibility(View.VISIBLE);
					loadMoreView.setText(getString(R.string.load_more));
					new Thread() {
						@Override
						public void run() {
							loadMore();
						}
					}.start();
				}
			}
			
			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				lastItem = firstVisibleItem - 2 + visibleItemCount;
			}
		});
		
  		if (chooseFriendType != AppContext.CHOOSE_FRIEND_THROWBOTTLE_TYPE) {
  			listView.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
					if (arg2 == adapter.getCount()) {
						return;
					}
					FriendEntry entry = friendList.get(arg2 - 1);
					if (entry.getButton_mode() == 5) {
						Intent intent = new Intent(ChooseFriendActivity.this, ExpandEditActivity.class);
						Bundle bundle = new Bundle();
						bundle.putString("from_type", AppContext.FORWARPIC_PICEX);
						bundle.putInt("picid", picid);
						bundle.putInt("pic_uid", pic_uid);
						bundle.putInt("fuid",entry.getUid());
						bundle.putString("return_type",return_type );	
						intent.putExtras(bundle);
						startActivity(intent);
						finish();
					}
				}
			});
  		}
  		
//  		mheaderView = LayoutInflater.from(this).inflate(
//				R.layout.friend_no_data_header, null);
		mNoDataTipsLayout = (RelativeLayout)findViewById(R.id.rl_nodata_tip);
		mNoDataTipsText1 = (TextView)findViewById(R.id.tv_nodata_tips);
		mNoDataTipsText2 = (TextView)findViewById(R.id.tv_nodata_tips_2);
		mNoDataTipsButton = (Button)findViewById(R.id.bt_nodata_try);
//		listView.addHeaderView(mheaderView);
  		
	}
	
	private void setUIbyType() {
		if (chooseFriendType == AppContext.CHOOSE_FRIEND_THROWBOTTLE_TYPE) {
  			confirmView.setVisibility(View.VISIBLE);
  		} else if (chooseFriendType == AppContext.CHOOSE_FRIEND_EXCHANGE_INFO_TYPE) {
  			confirmView.setVisibility(View.GONE);
  		} else if (chooseFriendType == AppContext.CHOOSE_FRIEND_FORWARD_BOTTLE_TYPE) {
  			confirmView.setVisibility(View.VISIBLE);
  		} else if (chooseFriendType == AppContext.CHOOSE_FRIEND_EXCHANGE_PHOTO_TYPE) {
  			confirmView.setVisibility(View.GONE);
  		} else if (chooseFriendType == AppContext.CHOOSE_FRIEND_FORWARD_PHOTO_TYPE) {
  			confirmView.setVisibility(View.VISIBLE);
  		}
		if (listType == 0) {
			friendGroupLayout.setVisibility(View.VISIBLE);
		} else {
			friendGroupLayout.setVisibility(View.GONE);
		}
	}
	
	@Override
	public void onClick(View v) {
		if (v == backView) {
			finish();
		} else if (v == confirmView) {//点击确定的时候，获取多选的好友
			List<Integer> friendUids = new ArrayList<Integer>();
			List<String> friendNicknames = new ArrayList<String>();
			for (FriendEntry entry : friendList) {
				if (entry.isSelected()) {
					friendUids.add(entry.getUid());
					friendNicknames.add(entry.getNickname());
				}
			}
			if (friendUids.isEmpty()) {
				onToast(getString(R.string.choose_friend_no_selected));
				return;
			} else {
				int[] uids = new int[friendUids.size()];
				for (int i = 0;i < friendUids.size();i++) {
					uids[i] = friendUids.get(i);
				}
				String[] nicknames = new String[friendNicknames.size()];
				friendNicknames.toArray(nicknames);
				Intent intent = new Intent(this, ExpandEditActivity.class);
				Bundle extras = new Bundle();
				String fuids = StringUtil.intArraysToString(uids);
				if (chooseFriendType == AppContext.CHOOSE_FRIEND_FORWARD_BOTTLE_TYPE) {//转发瓶子
					extras.putString("from_type", AppContext.FORWARD_BT);
					extras.putInt("bttype_id", bottleId);
				} else if (chooseFriendType == AppContext.CHOOSE_FRIEND_FORWARD_PHOTO_TYPE) {//转发照片
					extras.putString("from_type", AppContext.FORWARD_PHOTO);
					extras.putInt("picid", picid);
					if (select_mode == 1) {
						UICore.eventTask(this, this, recommend_photo, "", fuids);
						return;
					}
				}
				extras.putString("return_type",return_type );	
				extras.putString("fuids", fuids.substring(0, fuids.length()));
				extras.putStringArray("nicknames", nicknames);
				intent.putExtras(extras);
				startActivity(intent);
				finish();
			}
		} else if (v == friendGroupLayout) {
			doSelectGroupAction();
		}
	}
	
	@Override
	public void execute(int mes, Object obj) {
		switch (mes) {
		case init_friend_info:
			initFriendInfo();
			break;
		case load_more_datas:
			loadMore();
			break;
		case init_has_exs:
			getHasExs();
			break;
		case recommend_photo:
			recommendPhoto(obj.toString());
			break;
		default:
			break;
		}
	}
	
	private void updateUI() {
		if (friendList != null && !friendList.isEmpty()) {
			adapter = new FriendAdapter();
			listView.setAdapter(adapter);
		}
		if (chooseFriendType == AppContext.CHOOSE_FRIEND_THROWBOTTLE_TYPE) {
			if (groupNames != null && groupNames.length > 0) {
				groupNameView.setText("(" + groupNames[groupItem] + ")");
			}
		}
		if (show_config.getShow_config() != null) {
			findViewById(R.id.choose_friend_tips_layout).setVisibility(View.VISIBLE);
			((TextView) findViewById(R.id.tv_profile_tips)).setText(getString(R.string.throw_bottle_setting_tips) + show_config.getShow_config());
		} else {
			findViewById(R.id.choose_friend_tips_layout).setVisibility(View.GONE);
		}
		listView.onRefreshComplete();
	}
	
	private void initFriendInfo() {
		StringBuffer url = new StringBuffer(UrlConfig.get_selectusers);
		url.append("?clitype=2");
		url.append("&language=" + AppContext.language);
		url.append("&login_uid=" + AppContext.getInstance().getLogin_uid());
		url.append("&login_token=" + AppContext.getInstance().getLogin_token());
		url.append("&list_type=" + listType);
		url.append("&count=" + count);
		url.append("&page=" + page);
		if (listType == 1) {
			url.append("&exchange_type=" + exchange_type);
		}
		if (listType == 0) {
			url.append("&groupid=" + groupId);
		}
		url.append("&select_mode=" + select_mode);
		try {
			String result = HttpUtils.doGet(url.toString());
			Gson gson = new Gson();
			InitFriendInfo friendGson = gson.fromJson(result, InitFriendInfo.class);
			show_config = friendGson.getShow_config();
			int authok = friendGson.getResults().getAuthok();
			if (authok == 0) {
				String errmsg = friendGson.getResults().getErrmsg();
				Message msg = Message.obtain(handler, init_friend_info_error, errmsg);
				handler.sendMessage(msg);
			} else {
				friendList = friendGson.getUsers_list();
				friendGroupList = friendGson.getGroups_list();
				if (friendGroupList != null && !friendGroupList.isEmpty()) {
					groupNames = new String[friendGroupList.size() + 1];
					groupNames[0] = getString(R.string.choose_friend_allgroups);
					for (int i = 1;i < friendGroupList.size() + 1;i++) {
						groupNames[i] = friendGroupList.get(i - 1).getGroupname();
					}
					if (friendList != null && !friendList.isEmpty()) {
						handler.sendEmptyMessage(init_friend_info);	
					} else {
						if (listType == 0) {
							handler.sendEmptyMessage(init_friend_myfriend_no_data);
						} else {
							handler.sendEmptyMessage(init_friend_btfriend_no_data);
						}	
					}
					
				} else {
					if (friendList != null && !friendList.isEmpty()) {
						handler.sendEmptyMessage(init_friend_info);
					} else {
						if (listType == 0) {
							handler.sendEmptyMessage(init_friend_myfriend_no_data);
						} else {
							handler.sendEmptyMessage(init_friend_btfriend_no_data);
						}						
					}
					
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private void recommendPhoto(String fuids) {
		String url = UrlConfig.recommend_photo;
		HashMap<String, String> paramsMap = new HashMap<String, String>();
		paramsMap.put("login_uid", String.valueOf(AppContext.getInstance().getLogin_uid()));
		paramsMap.put("login_token", AppContext.getInstance().getLogin_token());
		paramsMap.put("picid", String.valueOf(picid));
		paramsMap.put("fuids", fuids);
		try {
			String result = HttpUtils.doPost(this, url, paramsMap);
			if (result != null) {
				JSONObject obj = new JSONObject(result);
				JSONObject resultObj = obj.getJSONObject("results");
				if (resultObj.getInt("success") == 1) {
					Message msg = Message.obtain(handler, recommend_photo, resultObj.get("successmsg"));
					handler.sendMessage(msg);
				} else {
					Message msg = Message.obtain(handler, recommend_photo, resultObj.get("errmsg"));
					handler.sendMessage(msg);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	private void loadMore() {
		StringBuffer url = new StringBuffer(UrlConfig.get_selectusers);
		url.append("?clitype=2");
		url.append("&language=" + AppContext.language);
		url.append("&login_uid=" + AppContext.getInstance().getLogin_uid());
		url.append("&login_token=" + AppContext.getInstance().getLogin_token());
		url.append("&list_type=" + listType);
		url.append("&count=" + count);
		url.append("&page=" + page);
		if (listType == 1) {
			url.append("&exchange_type=" + exchange_type);
		}
		if (listType == 0) {
			url.append("&groupid=" + groupId);
		}
		url.append("&select_mode=" + select_mode);
		
		try {
			List<FriendEntry> moreDatas;
			String result = HttpUtils.doGet(url.toString());
			Gson gson = new Gson();
			InitFriendInfo friendGson = gson.fromJson(result, InitFriendInfo.class);
			show_config = friendGson.getShow_config();
			int authok = friendGson.getResults().getAuthok();
			if (authok == 0) {
				String errmsg = friendGson.getResults().getErrmsg();
				Message msg = Message.obtain(handler, init_friend_info_error, errmsg);
				handler.sendMessage(msg);
			} else {
				moreDatas = friendGson.getUsers_list();
				if (moreDatas != null) {
					friendList.addAll(moreDatas);
				}
				handler.sendEmptyMessage(load_more_datas);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private void getHasExs() {
		StringBuffer url = new StringBuffer(UrlConfig.get_has_exs);
		url.append("?clitype=2");
		url.append("&language=" + AppContext.language);
		url.append("&login_uid=" + AppContext.getInstance().getLogin_uid());
		url.append("&login_token=" + AppContext.getInstance().getLogin_token());
		url.append("&ouid=" + ouid);
		
		try {
			String result = HttpUtils.doGet(url.toString());
			ServiceUtils.dout(TAG +":"+ result);
			if (result != null) {
	        	JSONObject object = new JSONObject(result);
	        	JSONObject resultObj = object.getJSONObject("results");
	        	int authok = resultObj.getInt("authok");
	        	if (authok == 0) {
	        		String errmsg = resultObj.getString("errmsg");
	        		Message msg = Message.obtain(handler, init_has_exs_error, errmsg);
	        		handler.sendMessage(msg);
	        	} else {
	        		JSONObject hasExsObj = object.getJSONObject("has_exs");
	        		if (chooseFriendType == AppContext.CHOOSE_FRIEND_EXCHANGE_INFO_TYPE) {
	        			int has_infoexs = hasExsObj.getInt("has_infoexs");
	        			if (has_infoexs == 1) {
	        				Intent intent = new Intent(this, ExchangeInfoDetailActivity .class);
	        				intent.putExtra("ouid", ouid);
	        				startActivity(intent);
	        			} else {
	        				handler.sendEmptyMessage(init_has_exs);
	        			}
	        		} else if (chooseFriendType == AppContext.CHOOSE_FRIEND_EXCHANGE_PHOTO_TYPE) {
	        			int has_picexs = hasExsObj.getInt("has_picexs");
	        			if (has_picexs == 1) {
	        				Intent intent = new Intent(this, ExchangePicDetailActivity.class);
	        				intent.putExtra("ouid", ouid);
	        				startActivity(intent);
	        			} else {
	        				handler.sendEmptyMessage(init_has_exs);
	        			}
	        		}
	        	}
	        }
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private void doSelectGroupAction() {
		final Context dialogContext = new ContextThemeWrapper(this, android.R.style.Theme_Light);
		String cancel = getString(R.string.bt_title_back);
		final ListAdapter adapter = new ArrayAdapter<String>(dialogContext,
				android.R.layout.simple_list_item_1, groupNames);
	
		final AlertDialog.Builder builder = new AlertDialog.Builder(dialogContext);
		builder.setTitle(getString(R.string.choose_friend_select_group));
		builder.setSingleChoiceItems(adapter, -1,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						groupItem = which;
						if (which != 0) {
							groupId = friendGroupList.get(which - 1).getGroupid();
						} else {
							groupId = 0;
						}
						groupNameView.setText("(" + groupNames[groupItem] + ")");
						UICore.eventTask(ChooseFriendActivity.this,
								ChooseFriendActivity.this, init_friend_info,
								getString(R.string.init_data), null);
					}
				});
		builder.setNegativeButton(cancel, new DialogInterface.OnClickListener() {
	
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
			
		});
		builder.create().show();
	}
	
	public class FriendAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			return friendList == null ? 0 : friendList.size() + 1;
		}

		@Override
		public Object getItem(int arg0) {
			return friendList == null ? null : friendList.get(arg0);
		}

		@Override
		public long getItemId(int arg0) {
			return arg0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup arg2) {
			if (position == getCount() - 1) {
				View view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.listfooter_more, null);
				progressBar = (ProgressBar) view.findViewById(R.id.pull_to_refresh_progress);
				loadMoreView = (TextView) view.findViewById(R.id.load_more);
				return view;
			}
			if (convertView != null && convertView.getId() == R.id.choose_friend_listitem_layout) {
				holder = (ViewHolder) convertView.getTag();
			} else {
				holder = new ViewHolder();
				convertView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.choose_friend_listitem, null);
				holder.avatar = (RemoteImageView) convertView.findViewById(R.id.choose_friend_listitem_avatar);
				holder.nickname = (TextView) convertView.findViewById(R.id.choose_friend_listitem_nickname);
				holder.mSex = (ImageView)convertView.findViewById(R.id.bt_sex);				
				holder.memo = (TextView) convertView.findViewById(R.id.choose_friend_listitem_memo);
				holder.address = (TextView) convertView.findViewById(R.id.choose_friend_listitem_address);
				holder.mood = (TextView) convertView.findViewById(R.id.choose_friend_listitem_mood);
				holder.isSelected = (Button) convertView.findViewById(R.id.choose_friend_listitem_isselected);
				convertView.setTag(holder);
			}
			final FriendEntry entry = friendList.get(position);
			if (entry != null) {
				holder.nickname.setText(entry.getNickname());
				int sex_res = entry.getSex() == 1 ? R.drawable.male:R.drawable.female;
				holder.mSex.setBackgroundResource(sex_res);
				holder.memo.setText(entry.getMemo());
				String html = "<font color=black>"+getString(R.string.user_info_doing)+"</font>";
				if (!TextUtils.isEmpty(entry.getDoing())) {
					holder.mood.setText(Html.fromHtml(html + entry.getDoing()));	
				}else {
					holder.mood.setVisibility(View.GONE);
				}
				
				if (entry.getCountry() != null && !entry.getCountry().equals("")) {
					if (AppContext.language == 1) {
						holder.address.setText(getString(R.string.user_from) + entry.getCountry() + "," + entry.getCity());
					} else {
						holder.address.setText(getString(R.string.user_from) + entry.getCity() + "," + entry.getCountry());
					}
				}
				holder.avatar.setDefaultImage(R.drawable.avatar_default_big);
				holder.avatar.setImageUrl(entry.getAvatar(), position, listView);
				
				if (entry.getButton_mode() == 0) {//已经照片交换 
					holder.isSelected.setBackgroundResource(R.drawable.btn_blue_try);
					holder.isSelected.setText(getString(R.string.exchange_bt_ex_photo));
					holder.isSelected.setVisibility(View.VISIBLE);
					holder.isSelected.setPadding(5, 5, 5, 5);
				} else if (entry.getButton_mode() ==1) {//未照片交换（1）
					holder.isSelected.setBackgroundResource(R.drawable.btn_red_try);
					holder.isSelected.setText(getString(R.string.exchange_bt_ex_photo));
					holder.isSelected.setVisibility(View.VISIBLE);
					holder.isSelected.setPadding(5, 5, 5, 5);
				} else if (entry.getButton_mode() == 2) {//已经资料交换（2）
					holder.isSelected.setBackgroundResource(R.drawable.btn_blue_try);
					holder.isSelected.setText(getString(R.string.exchange_bt_ex_profile));
					holder.isSelected.setVisibility(View.VISIBLE);
					holder.isSelected.setPadding(5, 5, 5, 5);
				} else if (entry.getButton_mode() == 3) {//未资料交换（3）
					holder.isSelected.setBackgroundResource(R.drawable.btn_red_try);
					holder.isSelected.setText(getString(R.string.exchange_bt_ex_profile));
					holder.isSelected.setVisibility(View.VISIBLE);
					holder.isSelected.setPadding(5, 5, 5, 5);
				} else if (entry.getButton_mode() == 4) {//多选（4）
					holder.isSelected.setVisibility(View.VISIBLE);
					if (entry.isSelected()) {
						holder.isSelected.setBackgroundResource(R.drawable.select_red);
					} else {
						holder.isSelected.setBackgroundResource(R.drawable.select_gray);
					}
				} else if (entry.getButton_mode() == 5) {
					holder.isSelected.setVisibility(View.GONE);
				}
			}
			holder.isSelected.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					if (entry.getButton_mode() == 0) {//已经照片交换 
						Intent intent = new Intent(ChooseFriendActivity.this, ExchangePicDetailActivity.class);
						intent.putExtra("ouid", entry.getUid());
						intent.putExtra("page", 1);
						startActivity(intent);
					} else if (entry.getButton_mode() ==1) {//未照片交换（1）
						Intent intentPhoto = new Intent(ChooseFriendActivity.this, ExpandEditActivity.class);
						Bundle bundlePhoto = new Bundle();
						bundlePhoto.putString("from_type", AppContext.APPLY_PICEX);
						bundlePhoto.putInt("ouid", entry.getUid());
						intentPhoto.putExtras(bundlePhoto);
						startActivity(intentPhoto);
						finish();
					} else if (entry.getButton_mode() == 2) {//已经资料交换（2）
						Intent intent = new Intent(ChooseFriendActivity.this, ExchangeInfoDetailActivity .class);
						intent.putExtra("ouid", entry.getUid());
						intent.putExtra("page", 1);
						startActivity(intent);
					} else if (entry.getButton_mode() == 3) {//未资料交换（3）
						Intent intentProfile = new Intent(ChooseFriendActivity.this, ExpandEditActivity.class);
						Bundle bundleProfile = new Bundle();
						bundleProfile.putString("from_type", AppContext.REPLY_INFOEX);
						bundleProfile.putInt("ouid", entry.getUid());
						bundleProfile.putString("reply_infoex_type", "apply");
						intentProfile.putExtras(bundleProfile);
						startActivity(intentProfile);
						finish();
					} else if (entry.getButton_mode() == 4) {//多选（4）
						Button view = (Button) v;
						if (entry.isSelected()) {
							view.setBackgroundResource(R.drawable.select_gray);
							entry.setSelected(false);
						} else {
							view.setBackgroundResource(R.drawable.select_red);
							entry.setSelected(true);
						}
					}
					
				}
			});
			holder.avatar.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					if (entry.getAvatar_click() == 1) {
						Intent intent = new Intent(ChooseFriendActivity.this, UserSpaceActivity.class);
						intent.putExtra("ouid", entry.getUid());
						startActivity(intent);
					}
				}
			});
			return convertView;
		}
	}
	
	public static class ViewHolder {
		public ImageView mSex;
		RemoteImageView avatar;
		TextView nickname;
		TextView memo;
		TextView address;
		TextView mood;
		Button isSelected;
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if (AppContext.getInstance().isFromExchangeTimeToChangeFriend()) {
				AppContext.getInstance().setFromExchangeTimeToChangeFriend(false);
			}
			if (AppContext.getInstance().isFromExchangeTime()) {
				AppContext.getInstance().setFromExchangeTime(false);
			}
		}
		return super.onKeyDown(keyCode, event);
	}
	@Override
	public boolean handleMessage(Message msg) {
		try {
			LanguageConfigTable languageConfigTable = null;
			LanguageConfig languageCon = null;
			switch (msg.what) {
			case init_friend_info:
				mNoDataTipsLayout.setVisibility(View.GONE);
				updateUI();
				break;
			case init_friend_info_error:
				onToast((String) msg.obj);
				break;
			case load_more_datas:
				adapter.notifyDataSetChanged();
				progressBar.setVisibility(View.GONE);
				loadMoreView.setText(getString(R.string.more_data));
				break;
			case init_has_exs:
				if (chooseFriendType == AppContext.CHOOSE_FRIEND_EXCHANGE_INFO_TYPE) {
					Intent intent = new Intent(ChooseFriendActivity.this, ExpandEditActivity.class);
					Bundle bundle = new Bundle();
					bundle.putString("from_type", AppContext.REPLY_INFOEX);
					bundle.putInt("ouid", ouid);
					bundle.putString("reply_infoex_type", "apply");
					bundle.putInt("ouid", ouid);
					intent.putExtras(bundle);
					startActivity(intent);
					finish();
				} else if (chooseFriendType == AppContext.CHOOSE_FRIEND_EXCHANGE_PHOTO_TYPE) {
					Intent intent = new Intent(ChooseFriendActivity.this, ExpandEditActivity.class);
					Bundle bundle = new Bundle();
					bundle.putString("from_type", AppContext.APPLY_PICEX);
					bundle.putString("reply_picex_type", "apply");
					bundle.putInt("ouid", ouid);
					intent.putExtras(bundle);
					startActivity(intent);
					finish();
				}
				break;
			case refresh_friend:
				adapter.notifyDataSetChanged();
				listView.onRefreshComplete();
				break;
			case init_has_exs_error:
				onToast((String)msg.obj);
				break;
			case init_friend_myfriend_no_data:
				mNoDataTipsLayout.setVisibility(View.VISIBLE);
				
				languageConfigTable = new LanguageConfigTable();
				languageCon = languageConfigTable.getBottleLanguageConfig();
				
				String friendTips1 = null;
				String friendTips2 = null;
				if (AppContext.language == 1) {
					friendTips1 = languageCon.getWithout_friend_tip_cn();
					friendTips2 = languageCon.getWithout_friend_tip_2_cn();
				}else {
					friendTips1 = languageCon.getWithout_friend_tip_en();
					friendTips2 = languageCon.getWithout_friend_tip_2_en();
				}
				mNoDataTipsText1.setText(friendTips1);
				mNoDataTipsText2.setText(friendTips2);
				mNoDataTipsButton.setText(TextUtil.R("friend_nodata_tip_bt_maybeknow"));
				mNoDataTipsButton.setOnClickListener(new View.OnClickListener() {
					
					@Override
					public void onClick(View paramView) {
						Intent intent = new Intent(ChooseFriendActivity.this, BindInviteActivity.class);
						startActivity(intent);
					}
				});
				break;
			case init_friend_btfriend_no_data:
				mNoDataTipsLayout.setVisibility(View.VISIBLE);
				languageConfigTable = new LanguageConfigTable();
				languageCon = languageConfigTable.getBottleLanguageConfig();
				String btfriendTips1 = null;
				String btfriendTips2 = null;
				if (AppContext.language == 1) {
					btfriendTips1 = languageCon.getWithout_btfriend_tip_cn();
					btfriendTips2 = languageCon.getWithout_btfriend_tip_2_cn();
				}else {
					btfriendTips1 = languageCon.getWithout_btfriend_tip_en();
					btfriendTips2 = languageCon.getWithout_btfriend_tip_2_en();
				}
				
				mNoDataTipsText1.setText(btfriendTips1);
				mNoDataTipsText2.setText(btfriendTips2);
				mNoDataTipsButton.setText(TextUtil.R("bottle_txt_title_gain"));
				mNoDataTipsButton.setOnClickListener(new View.OnClickListener() {
					
					@Override
					public void onClick(View paramView) {
						Intent tryIntent = new Intent(
								ChooseFriendActivity.this,
								ChooseBottleActivity.class);
						tryIntent.putExtra("type", "try");
						startActivity(tryIntent);
					}
				});
				break;
			case recommend_photo:
				onToast((String) msg.obj);
				finish();
				break;
			case error:
				onToast((String) msg.obj);
				break;
			default:
				break;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}
	
	
}
